from PIL import Image, ImageSequence, ImageEnhance
import numpy as np

def compress_gif_to_16x16(image_path, contrast_factor=1.0):
    # 打开GIF文件
    img = Image.open(image_path)
    
    # 获取所有帧
    frames = []
    for frame in ImageSequence.Iterator(img):
        # 将图像转换为RGB模式以防止模式错误
        frame_rgb = frame.convert('RGB')
        
        # 增强对比度
        enhancer = ImageEnhance.Contrast(frame_rgb)
        frame_contrasted = enhancer.enhance(contrast_factor)
        
        # 将每一帧压缩到16x16分辨率，使用LANCZOS作为重采样过滤器
        frame_resized = frame_contrasted.resize((16, 16), Image.LANCZOS)
        
        frames.append(frame_resized)
    
    # 创建一个4D数组，保存所有帧的RGB888颜色数据
    num_frames = len(frames)
    display_data = np.zeros((num_frames, 16, 16, 3), dtype=np.uint8)
    
    # 将每帧的像素值存储到数组中
    for frame_idx, frame in enumerate(frames):
        for row in range(16):
            for col in range(16):
                r, g, b = frame.getpixel((col, row))
                display_data[frame_idx][row][col][0] = r  # 红色通道
                display_data[frame_idx][row][col][1] = g  # 绿色通道
                display_data[frame_idx][row][col][2] = b  # 蓝色通道
    
    return display_data

def write_array_to_h_file(data, filename):
    # 获取帧数
    num_frames = data.shape[0]
    
    with open(filename, 'w') as file:
        # 写入.h文件的头信息
        file.write("#ifndef DISPLAY_DATA_H\n")
        file.write("#define DISPLAY_DATA_H\n\n")
        file.write(f"uint8_t display_data[{num_frames}][16][16][3] = {{\n")
        
        # 写入每帧的像素数据
        for frame in range(num_frames):
            file.write(f"    {{  // Frame {frame}\n")
            for row in range(16):
                file.write("        {")
                for col in range(16):
                    r, g, b = data[frame][row][col]
                    if col < 15:
                        file.write(f"{{{r}, {g}, {b}}}, ")
                    else:
                        file.write(f"{{{r}, {g}, {b}}}")
                if row < 15:
                    file.write("},\n")
                else:
                    file.write("}\n")
            if frame < num_frames - 1:
                file.write("    },\n")
            else:
                file.write("    }\n")
        file.write("};\n\n")
        file.write("#endif // DISPLAY_DATA_H\n")

# 调用函数并将C数组写入.h文件
image_path = 'xin2.gif'  # 替换为你的GIF文件路径
data = compress_gif_to_16x16(image_path, contrast_factor=1.5)  # contrast_factor可调节对比度，1.0为原始对比度，>1增加对比度
write_array_to_h_file(data, 'display_data.h')
